#include "StdAfx.h"
#include "PlayerController.h"
#include "EntityEvents.h"

#include "../kernel.h"

extern Kernel* g_kernel;

/*-------------------------------------------------------------
    Define shortcuts
--------------------------------------------------------------*/
#define JOYSTICK_XAXIS ( g_kernel->GetInput()->GetJoystickX() )
#define JOYSTICK_YAXIS ( g_kernel->GetInput()->GetJoystickY() )

#define JOYSTICK_BUTTON( str ) ( g_kernel->GetInput()->IsJoystickButtonDown( g_kernel->GetCvars()->GetFloatValue( str ) ) )
#define KEY_BUTTON( str ) ( g_kernel->GetInput()->IsKeyDown( g_kernel->GetCvars()->GetFloatValue( str ) ) )
#define KEY_BUTTONSTAMP( str ) ( g_kernel->GetInput()->IsKeyDown( g_kernel->GetCvars()->GetFloatValue( str ), true ) )

#define TIME (g_kernel->GetTime())

#include <math.h>

PlayerController::PlayerController(void)
{
    m_oldButtons = 0;
}

PlayerController::~PlayerController(void)
{
}

/** Gather input, and send events */
void PlayerController::GatherEvents()
{
    int buttons = 0;

    int registerInput = g_kernel->GetCvars()->GetFloatValue( "i_registerInput" );
    if ( !registerInput ) 
        return;

    // TEMP - Testing joystick module
    if ( g_kernel->GetInput()->JoystickEnabled() )
    {
        if ( JOYSTICK_XAXIS > 15000 )
            buttons |= BUTTON_RIGHT;
        else if ( JOYSTICK_XAXIS < -20000 )
            buttons |= BUTTON_LEFT;
        if ( JOYSTICK_YAXIS > 15000 )
            buttons |= BUTTON_DOWN;
        else if ( JOYSTICK_YAXIS < -20000 )
            buttons |= BUTTON_UP;

        if ( JOYSTICK_BUTTON(  "+j_attack1" ) ) {
            buttons |= BUTTON_ATTACK1;
        }
        if ( JOYSTICK_BUTTON( "+j_use" ) ) {
            buttons |= BUTTON_USE;
        }
        if ( JOYSTICK_BUTTON( "+j_strafe" ) )
            buttons |= BUTTON_STRAFE;
    }

    // check each button for activation...
    if ( KEY_BUTTONSTAMP( "+up" ) ) {
        buttons |= BUTTON_UP;
    } else if ( KEY_BUTTONSTAMP( "+down" ) ) {
        buttons |= BUTTON_DOWN;
    }

    if ( KEY_BUTTONSTAMP( "+left" ) ) {
        buttons |= BUTTON_LEFT;
    } else if ( KEY_BUTTONSTAMP( "+right" ) ) {
        buttons |= BUTTON_RIGHT;
    } 
    if ( KEY_BUTTON( "+attack1" ) ) {
        buttons |= BUTTON_ATTACK1;
    }
    if ( KEY_BUTTON( "+use" ) ) {
        buttons |= BUTTON_USE;
    }
    if ( KEY_BUTTONSTAMP( "+strafe" ) ) {
        buttons |= BUTTON_STRAFE;
    }
    // dispatch the message
    if ( m_oldButtons != buttons )
    {
        //g_kernel->LPrintf(" Dispatching Movement event %d vs %d", buttons, m_oldButtons );
        IEvent evnt( EVT_ENTITY, TIME, new EntityEvents(0, buttons), LT_ENTITY );

        // Trigger this event NOW since the player updates every 1/100 of a second
        EventManager::GetInstance()->TriggerEvent( evnt );

        m_oldButtons = buttons;
    }
}
